import { JwtStrategy, fromHeader } from 'passport-jwt'
import passport from 'passport'
import { config } from '../config'
export const setJWT = ({ userName, userId }) => {
  const opts = {
    jwtFromRequest: () => {
      return fromHeader('authorization')
    },
    secretOrKey: config.JWT_SECRET,
    algorithms: [config.JWT_ALG],
    // 将请求对象传递回回调，这样我们就可以将JWT附加到它。
    // 如果 true，请求将被传递到验证回调。 verify( req，jwt_payload，done_callback )
    passReqToCallback: true,
  }

  return passport.use(
    new JwtStrategy(opts, async function (req, jwt_payload, done) {
      try {
        done(null, { userName, userId })
      } catch (e) {
        return done(e)
      }
    }),
  )
}
